#ifndef _UNIT_MGR_H_
#define _UNIT_MGR_H_

#include <stdexcept> 

const unsigned int MAX_UNIT_INSTANCE_NUMBER = 3;
template <class T>
class UnitMgr
{
public:
	explicit UnitMgr(unsigned int maxNumberOfUnit);
	const T ** getUnitTab(); 
	void storeUnit(const T* pNewUnit);
	unsigned int getNumberOfUnit() const;
private:
	bool isUnitTabInitialized;
	unsigned int curNumberOfUnit;
        unsigned int maxNumberOfUnit;
	const T * pUnitTab[MAX_UNIT_INSTANCE_NUMBER];
};


template <class T>
unsigned int UnitMgr<T>::getNumberOfUnit() const
{
        return curNumberOfUnit;
}

template <class T>
UnitMgr<T>::UnitMgr(unsigned int maxNumberOfUnit)
:curNumberOfUnit(0),maxNumberOfUnit(maxNumberOfUnit)
{
	if (maxNumberOfUnit >  MAX_UNIT_INSTANCE_NUMBER)
	{
		throw std::invalid_argument("max unit managment number limited");
	}
}

template <class T>
const T  **  UnitMgr<T>::getUnitTab() 
{
	if (!isUnitTabInitialized)
	{
		pUnitTab[0]->initUnitTab();
		isUnitTabInitialized = true;
	}
	return pUnitTab;
}

template <class T>
void UnitMgr<T>::storeUnit(const T* pNewUnit)
{
	if (curNumberOfUnit == maxNumberOfUnit)
	{
		throw std::invalid_argument("Max number of Unit reached");
	}
        int i;
	unsigned int curNumberOfUnitBeforeInsert = curNumberOfUnit;
	curNumberOfUnit++;
        if (0 == curNumberOfUnitBeforeInsert)
        {
                pUnitTab[0] = pNewUnit;
                return;
        }
        if (1 == curNumberOfUnitBeforeInsert)
        {
                if(*pUnitTab[0] > *pNewUnit)
                {
                        pUnitTab[1] = pNewUnit;
                }
                else
                {
                        pUnitTab[1] = pUnitTab[0];
                        pUnitTab[0] = pNewUnit;
                }
                return;
        }

        for (i = curNumberOfUnitBeforeInsert - 1; (i >= 0) && (*pNewUnit  >  *pUnitTab[i]); i--)
        {
                pUnitTab[i + 1] = pUnitTab[i];
        }
        pUnitTab[i+1] = pNewUnit;
        return;
}
#endif
